package com.battcn.platform.controller.crawler;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.battcn.platform.entity.AjaxJson;
import com.battcn.platform.entity.crow.ProxyIp;
import com.battcn.platform.mapper.crow.ProxyIpMapper;
import com.battcn.platform.service.webmagic.CrawlerServeice;

import io.swagger.annotations.Api;

/**
 * 爬虫请求 Created by yanglei on 17/10/21.
 */
@Controller
@RequestMapping("/Crawler")
@Api(tags = "1.4", description = "爬虫请求")
public class CrawlerController {
	@Autowired
	CrawlerServeice crawlerServeice;
	@Autowired
	ProxyIpMapper proxyIpMapper;
	
	protected AtomicInteger stat = new AtomicInteger(0);

	@RequestMapping(value = "/getMovies")
	@ResponseBody
	public AjaxJson getMovies() {
		AjaxJson data = new AjaxJson();
		try {
			if(stat.get()==1){
				return new AjaxJson("爬虫任务正在执行！", false);
			}
			stat.incrementAndGet();
			crawlerServeice.getMovies();
			stat.compareAndSet(stat.get(), 0);
			data.setMsg("电影爬虫成功");
			data.setSuccess(true);
		} catch (Exception e) {
			stat.compareAndSet(stat.get(), 0);
			data.setSuccess(false);
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new AjaxJson("爬虫任务失败！", false);
		}

		return data;
	}
	
	@RequestMapping(value = "/spiderStop")
	@ResponseBody
	public AjaxJson spiderStop() {
		AjaxJson data = new AjaxJson();
		try {
			if(stat.get()==0){
				return new AjaxJson("没有爬虫任务正在执行！请添加爬虫任务！", false);
			}
			crawlerServeice.spiderStop();
			stat.compareAndSet(stat.get(), 0);
			data.setMsg("停止爬虫成功");
			data.setSuccess(true);
		} catch (Exception e) {
			data.setSuccess(false);
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return data;
	}
	
	@RequestMapping(value = "/CrawlerByUrl")
	@ResponseBody
	public AjaxJson CrawlerByUrl(String url) {
		AjaxJson data = new AjaxJson();
		try {
			url=url.trim();
			if(stat.get()==1){
				return new AjaxJson("爬虫任务正在执行！", false);
			}
			stat.incrementAndGet();
			data=crawlerServeice.CrawlerByUrl(url);
			stat.compareAndSet(stat.get(), 0);
		} catch (Exception e) {
			
			stat.compareAndSet(stat.get(), 0);
			data.setSuccess(false);
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new AjaxJson("爬虫任务失败！", false);
		}

		return data;
	}

}
